package com.west.common.helper;

import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.os.SystemClock;
import android.text.TextUtils;
import android.view.View;

import com.west.common.base.config.BaseApplication;
import com.west.common.bean.Constants;
import com.west.common.bean.User;
import com.west.common.uitils.StringUtils;
import com.west.common.uitils.TLog;


/**
 * 账户辅助类，
 * 用于更新用户信息和保存当前账户等操作
 */
public final class AccountHelper {

    private static final String TAG = AccountHelper.class.getSimpleName();
    private User user;
    private Application application;

    @SuppressLint("StaticFieldLeak")
    private static AccountHelper instances;

    private AccountHelper(Application application) {
        this.application = application;
    }

    public static void init(Application application) {
        if (instances == null)
            instances = new AccountHelper(application);
        else {
            // reload from source
            instances.user = SharedPreferencesHelper.loadFormSource(instances.application, User.class);
            TLog.d(TAG, "init reload:" + instances.user);
        }
    }

    public static boolean isLogin() {
        return !TextUtils.isEmpty(getUserId()) && !TextUtils.isEmpty(getToken());
    }

    public static String getUserFlag(){
        if(!isLogin()){
            return null;
        }
        return getUser().getFlag();
    }

    public static boolean isBindTaobao(){
        if(!StringUtils.isNull(getUser().getPayno()) && StringUtils.isNull(getUser().getPaynoName())){
            return true;
        }
        return false;
    }

    public static String getUserId() {
        return TextUtils.isEmpty(getUser().getUserId()) ? "" : getUser().getUserId();
    }

    public static String getRongyunToken() {
        return TextUtils.isEmpty(getUser().getRongtoken()) ? "" : getUser().getRongtoken();
    }

    public static String getToken() {
        return TextUtils.isEmpty(getUser().getToken()) ? "" : getUser().getToken();
    }

    public static String getRegId() {
        String regId = SharedPreferencesHelper.get(BaseApplication.getInstance(), "regId", "");
        return regId;
    }

    public static void setRegId(String regId) {
        if(!TextUtils.isEmpty(regId)){
            SharedPreferencesHelper.set(BaseApplication.getInstance(), "regId", regId);
        }
    }

    public synchronized static User getUser() {
        if (instances == null) {
            TLog.error("AccountHelper instances is null, you need call init() method.");
            return new User();
        }
        if (instances.user == null)
            instances.user = SharedPreferencesHelper.loadFormSource(instances.application, User.class);
        if (instances.user == null)
            instances.user = new User();
        return instances.user;
    }

    public static boolean updateUserCache(User user) {
        if (user == null)
            return false;
        instances.user = user;
        return SharedPreferencesHelper.save(instances.application, user);
    }

    public static void clearUserCache() {
        instances.user = null;
        SharedPreferencesHelper.remove(instances.application, User.class);
    }

    public static boolean login(final User user) {
        int count = 10;
        boolean saveOk;
        // 保存缓存
        while (!(saveOk = updateUserCache(user)) && count-- > 0) {
            SystemClock.sleep(100);
        }
        return saveOk;
    }

    /**
     * 退出登陆操作需要传递一个View协助完成延迟检测操作
     *
     * @param view     View
     * @param runnable 当清理完成后回调方法
     */
    public static void logout(final View view, final Runnable runnable) {
        // 清除用户缓存
        clearUserCache();
        // 等待缓存清理完成
        view.postDelayed(new Runnable() {
            @Override
            public void run() {
                view.removeCallbacks(this);
                User user = SharedPreferencesHelper.load(instances.application, User.class);
                // 判断当前用户信息是否清理成功
                if (user == null || TextUtils.isEmpty(user.getUserId())) {
                    clearAndPostBroadcast(instances.application);
                    runnable.run();
                } else {
                    view.postDelayed(this, 200);
                }
            }
        }, 200);

    }

    /**
     * 当前用户信息清理完成后调用方法清理服务等信息
     *
     * @param application Application
     */
    private static void clearAndPostBroadcast(Application application) {
        Context context = instances.application;
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        //activityManager.killBackgroundProcesses("com.west.headquarters.wanzhongfilm.ui.publish.service.FilmPublishService");
        //activityManager.killBackgroundProcesses("com.west.headquarters.wanzhongfilm.ui.publish.service.TweetPublishService");
        // 清除用户缓存
        clearUserCache();

        // Logou 广播
        Intent intent = new Intent(Constants.INTENT_ACTION_LOGOUT);
        context.sendBroadcast(intent);

    }
}
